package com.yhao.stock.common.service;

import com.alibaba.fastjson.JSONArray;
import com.gargoylesoftware.htmlunit.*;
import com.yhao.stock.common.listener.MyJSErrorListener;
import com.yhao.stock.common.utils.DateUtil;
import com.yhao.stock.common.utils.JsonUtil;
import com.yhao.stock.entity.HisData;
import com.yhao.stock.entity.HisData2023;
import com.yhao.stock.service.HisData2023Service;
import com.yhao.stock.service.HisDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author : yhao
 * @Date : 2023/11/10 - 11:38
 * @Desc : 搜狐API接口处理类
 */
@Slf4j
@Service
public class SHService {

    WebClient webClient = null;
    Map<String, String> additionalHeaders = null;
    @Autowired
    private HisData2023Service hisData2023Service;

    //初始化
    public SHService() {
        webClient = new WebClient(BrowserVersion.CHROME);//新建一个模拟谷歌Chrome浏览器的浏览器客户端对象
        webClient.getOptions().setThrowExceptionOnScriptError(false);//当JS执行出错的时候是否抛出异常, 这里选择不需要
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);//当HTTP的状态非200时是否抛出异常, 这里选择不需要
        webClient.getOptions().setActiveXNative(false);
        webClient.getOptions().setCssEnabled(false);//是否启用CSS, 因为不需要展现页面, 所以不需要启用
        webClient.getOptions().setJavaScriptEnabled(true); //很重要，启用JS。有些网站要开启！
        webClient.setAjaxController(new NicelyResynchronizingAjaxController());//很重要，设置支持AJAX
        webClient.getOptions().setTimeout(30000);
        // javascript 异常处理
        webClient.setJavaScriptErrorListener(new MyJSErrorListener());
        webClient.setJavaScriptTimeout(10000);
        webClient.getOptions().setThrowExceptionOnScriptError(false);
        webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);

        additionalHeaders = new HashMap<String, String>();
        additionalHeaders
                .put("User-Agent",
                        "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.104 Safari/537.36");
        additionalHeaders.put("Accept-Language", "zh-CN,zh;q=0.8");
        additionalHeaders.put("Accept", "*/*");

    }


    public void getFinanceInfo(String url) {
        try {
            WebRequest request = new WebRequest(new URL(url), HttpMethod.GET);
            request.setAdditionalHeaders(additionalHeaders);
            Page page = webClient.getPage(request);
            String response = page.getWebResponse().getContentAsString();
            log.warn("response-------->>>>>" + response);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Autowired
    private HisDataService hisDataService;

    /**
     * @param code
     * @param name
     * @return
     * @desc 获取当日信息
     */
    public boolean getTodayInfo(String code, String name) {
        final String today = DateUtil.getDate("yyyyMMdd");
        return getHisInfo(code, name, today, today);
    }

    /**
     * @param code
     * @param name
     * @param startDate
     * @param endDate
     * @return
     * @desc 获取历史数据
     */
    public boolean getHisInfo(String code, String name, String startDate, String endDate) {
        boolean saveBatch = false;
        String url = "https://q.stock.sohu.com/hisHq?code=cn_" + code + "&start=" + startDate + "&end=" + endDate;
        log.info("执行到这里了哈--------->" + url);
        HisData hisData = null;
        List<HisData> finalList = new ArrayList();
        HisData2023 hisData2023 = null;
        final ArrayList<HisData2023> hisData2023s = new ArrayList<>();
        String content = "";
        try {
            WebRequest request = new WebRequest(new URL(url), HttpMethod.GET);
            request.setAdditionalHeaders(additionalHeaders);
            Page page = webClient.getPage(request);
            String response = page.getWebResponse().getContentAsString();
            if (response != null && response.length() > 0) {
                List<Map<String, Object>> listObjectFir = (List<Map<String, Object>>) JSONArray.parse(response);
                final Map<String, Object> stringStringMap = listObjectFir.get(0);
                final JSONArray contents = (JSONArray) stringStringMap.get("hq");
                final Object[] objects = contents.toArray();

                String turnoverRate = "";
                for (Object object : objects) {
                    content = object.toString();
                    if (content == null || "".equals(content)) {
                        log.info("获取数据为空:============>>>" + code);
                        continue;
                    }
                    final List<Object> resultList = JsonUtil.jsonToList(content);
                    if (resultList.get(9).toString().contains("-")) {
                        turnoverRate = "0";
                    } else {
                        turnoverRate = resultList.get(9).toString().replace("%", "");
                    }

                    hisData = new HisData(code, name, resultList.get(0).toString(),
                            new BigDecimal(resultList.get(1).toString()),
                            new BigDecimal(resultList.get(2).toString()),
                            new BigDecimal(resultList.get(3).toString()),
                            new BigDecimal(resultList.get(4).toString().replace("%", "")),
                            new BigDecimal(resultList.get(5).toString()),
                            new BigDecimal(resultList.get(6).toString()),
                            new BigDecimal(resultList.get(7).toString()),
                            new BigDecimal(resultList.get(8).toString()),
                            new BigDecimal(turnoverRate),
                            DateUtil.getDate("yyyy-MM-dd"));
                    hisData2023 = new HisData2023(code, name, resultList.get(0).toString(),
                            new BigDecimal(resultList.get(1).toString()),
                            new BigDecimal(resultList.get(2).toString()),
                            new BigDecimal(resultList.get(3).toString()),
                            new BigDecimal(resultList.get(4).toString().replace("%", "")),
                            new BigDecimal(resultList.get(5).toString()),
                            new BigDecimal(resultList.get(6).toString()),
                            new BigDecimal(resultList.get(7).toString()),
                            new BigDecimal(resultList.get(8).toString()),
                            new BigDecimal(turnoverRate),
                            LocalDateTime.now());
                    finalList.add(hisData);
                    hisData2023s.add(hisData2023);
                }

                log.info("数据总长度===>>>" + finalList.size());
                int batchSize = 200;
                for (int i = 0; i < finalList.size(); i += batchSize) {
                    List<HisData> subList = finalList.subList(i, Math.min(i + batchSize, finalList.size()));
                    saveBatch = hisDataService.saveBatch(subList);
                }

                for (int i = 0; i < hisData2023s.size(); i += batchSize) {
                    List<HisData2023> subList = hisData2023s.subList(i, Math.min(i + batchSize, hisData2023s.size()));
                    saveBatch = hisData2023Service.saveBatch(subList);
                }

                // 随机休眠
                Thread.sleep(new Random().nextInt(1000) + 3000);

                log.info("saveBatch执行完成了");
            }
        } catch (Exception e) {
            log.error("content==========>>>" + content);
            // e.printStackTrace();

            log.error("url解析错误：" + url);
        }
        return saveBatch;
    }

    /**
     * @param code
     * @param name
     * @param startDate
     * @param endDate
     * @return
     * @desc 按年获取历史信息
     */
    public boolean getHisInfoByYear(String code, String name, String startDate, String endDate) {
        boolean saveBatch = false;
        String url = "https://q.stock.sohu.com/hisHq?code=cn_" + code + "&start=" + startDate + "&end=" + endDate;
        log.info("执行到这里了哈--------->" + url);
        HisData2023 hisData2023 = null;
        final ArrayList<HisData2023> hisData2023s = new ArrayList<>();
        String content = "";
        try {
            WebRequest request = new WebRequest(new URL(url), HttpMethod.GET);
            request.setAdditionalHeaders(additionalHeaders);
            Page page = webClient.getPage(request);
            String response = page.getWebResponse().getContentAsString();
            if (response != null && response.length() > 0) {
                List<Map<String, Object>> listObjectFir = (List<Map<String, Object>>) JSONArray.parse(response);
                final Map<String, Object> stringStringMap = listObjectFir.get(0);
                final JSONArray contents = (JSONArray) stringStringMap.get("hq");
                final Object[] objects = contents.toArray();

                String turnoverRate = "";
                for (Object object : objects) {
                    content = object.toString();
                    if (content == null || "".equals(content)) {
                        log.info("获取数据为空:============>>>" + code);
                        continue;
                    }
                    final List<Object> resultList = JsonUtil.jsonToList(content);
                    if (resultList.get(9).toString().contains("-")) {
                        turnoverRate = "0";
                    } else {
                        turnoverRate = resultList.get(9).toString().replace("%", "");
                    }

                    hisData2023 = new HisData2023(code, name, resultList.get(0).toString(),
                            new BigDecimal(resultList.get(1).toString()),
                            new BigDecimal(resultList.get(2).toString()),
                            new BigDecimal(resultList.get(3).toString()),
                            new BigDecimal(resultList.get(4).toString().replace("%", "")),
                            new BigDecimal(resultList.get(5).toString()),
                            new BigDecimal(resultList.get(6).toString()),
                            new BigDecimal(resultList.get(7).toString()),
                            new BigDecimal(resultList.get(8).toString()),
                            new BigDecimal(turnoverRate),
                            LocalDateTime.now());
                    hisData2023s.add(hisData2023);
                }

                int batchSize = 200;
                for (int i = 0; i < hisData2023s.size(); i += batchSize) {
                    List<HisData2023> subList = hisData2023s.subList(i, Math.min(i + batchSize, hisData2023s.size()));
                    saveBatch = hisData2023Service.saveBatch(subList);
                }

                // 随机休眠
                Thread.sleep(new Random().nextInt(1000) + 3000);

                log.info("saveBatch执行完成了");
            }
        } catch (Exception e) {
            log.error("content==========>>>" + content);
            e.printStackTrace();
            log.error("url解析错误：" + url);
        }
        return saveBatch;
    }
}
